<template>
  <div class="bg-gray-50 min-h-screen">
    <!-- 顶部导航栏 -->
    <header class="bg-white border-b border-gray-200 sticky top-0 z-50">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="flex items-center justify-between h-16">
          <!-- Logo和身份标识 -->
          <div class="flex items-center gap-3">
            <div class="flex items-center gap-2">
              <div class="w-10 h-10 bg-blue-500 rounded-lg overflow-hidden">
                <img src="../../../头像.jpg" alt="头像" class="w-full h-full object-cover" />
              </div>
              <span class="text-lg font-semibold text-gray-900">校园快递代拿</span>
            </div>
            <span class="px-3 py-1 bg-blue-100 text-blue-700 text-sm rounded-full">下单者</span>
          </div>

          <!-- 右侧按钮 -->
          <HeaderActions />
        </div>
      </div>
    </header>

    <!-- 标签页导航 -->
    <div class="bg-white border-b border-gray-200">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <nav class="flex gap-8">
          <button class="py-4 px-1 border-b-2 border-blue-500 text-blue-600 font-medium">发布订单</button>
          <button class="py-4 px-1 border-b-2 border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300" @click="$router.push('/order/my')">我的订单</button>
          <button class="py-4 px-1 border-b-2 border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300" @click="$router.push('/order/profile')">我的主页</button>
        </nav>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <main class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <!-- 发布订单表单 -->
      <div class="bg-white rounded-lg shadow-sm p-6 mb-8">
        <h2 class="text-xl font-semibold text-gray-900 mb-6">发布代拿订单</h2>

        <form class="space-y-8" @submit.prevent="handleSubmit">
          <!-- 物品信息 -->
          <div>
            <h3 class="text-base font-medium text-gray-900 mb-4">物品信息</h3>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
              <div>
                <label class="block text-sm text-gray-700 mb-2">物品类型</label>
                <select v-model="form.itemType" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                  <option value="">请选择物品类型</option>
                  <option value="express">快递包裹</option>
                  <option value="food">外卖食品</option>
                  <option value="document">文件资料</option>
                  <option value="other">其他物品</option>
                </select>
              </div>
              <div>
                <label class="block text-sm text-gray-700 mb-2">物品数量</label>
                <input v-model="form.itemCount" type="text" placeholder="请输入物品数量" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" />
              </div>
            </div>
            <div>
              <label class="block text-sm text-gray-700 mb-2">物品描述</label>
              <textarea v-model="form.itemDesc" rows="3" placeholder="请简要描述物品信息（如：快递大小、是否易碎等）" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-none"></textarea>
            </div>
          </div>

          <!-- 取件信息 -->
          <div>
            <h3 class="text-base font-medium text-gray-900 mb-4">取件信息</h3>
            <div class="mb-4">
              <label class="block text-sm text-gray-700 mb-2">取件地点</label>
              <select v-model="form.pickupLocation" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                <option value="">请选择取件地点</option>
                <option value="一期丰巢">一期丰巢</option>
                <option value="一期妈妈驿站">一期妈妈驿站</option>
                <option value="二期校园邮局">二期校园邮局</option>
                <option value="其他">其他</option>
              </select>
            </div>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label class="block text-sm text-gray-700 mb-2">取件码</label>
                <input v-model="form.pickupRef" type="text" placeholder="例如 A1-11-1111" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" />
              </div>
              <div>
                <label class="block text-sm text-gray-700 mb-2">期望取件时间</label>
                <div class="flex gap-3 items-center">
                  <label class="flex items-center gap-2 text-sm text-gray-700">
                    <input type="radio" v-model="useTimeRange" :value="true" /> 使用今天的时间范围
                  </label>
                  <label class="flex items-center gap-2 text-sm text-gray-700">
                    <input type="radio" v-model="useTimeRange" :value="false" /> 选择具体时间
                  </label>
                </div>
                <div v-if="useTimeRange" class="mt-2">
                  <select v-model="form.pickupRange" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                    <option value="">请选择今天的时间范围</option>
                    <option value="morning">上午(08:00-12:00)</option>
                    <option value="afternoon">下午(12:00-18:00)</option>
                    <option value="evening">晚上(18:00-22:00)</option>
                  </select>
                </div>
                <div v-else class="mt-2">
                  <input v-model="form.pickupTime" type="datetime-local" placeholder="请选择期望取件时间"
                    class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" />
                </div>
              </div>
            </div>
          </div>

          <!-- 送达信息 -->
          <div>
            <h3 class="text-base font-medium text-gray-900 mb-4">送达信息</h3>
            <div class="mb-4">
              <label class="block text-sm text-gray-700 mb-2">送达地点</label>
              <select v-model="form.dropoffLocation" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                <option value="">请选择送达地点</option>
                <option v-for="n in 13" :key="n" :value="`${n}栋`">{{ n }}栋</option>
              </select>
            </div>
            <div>
              <label class="block text-sm text-gray-700 mb-2">详细地址</label>
              <input v-model="form.dropoffDetail" type="text" placeholder="请输入详细地址（如：XX宿舍楼XX房间号）" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" />
            </div>
          </div>

          <!-- 其他信息 -->
          <div>
            <h3 class="text-base font-medium text-gray-900 mb-4">其他信息</h3>
            <div>
              <label class="block text-sm text-gray-700 mb-2">备注信息</label>
              <textarea v-model="form.remark" rows="3" placeholder="有其他特殊要求请在此说明（选填）" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-none"></textarea>
            </div>
          </div>

          <!-- 价格信息 -->
          <div class="border-t border-gray-200 pt-6">
            <div class="flex items-end gap-4 mb-6">
              <div class="flex-1">
                <label class="block text-sm text-gray-700 mb-2">订单总价(¥)</label>
                <input v-model.number="form.totalPrice" type="number" step="0.01" min="0" placeholder="请输入本单总价"
                  class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" />
              </div>
              <div class="text-right pb-2">
                <div class="text-gray-500 text-sm">将保存为本单建议费用</div>
                <div class="text-2xl font-bold text-blue-600">¥{{ Number(form.totalPrice || 0).toFixed(2) }}</div>
              </div>
            </div>
            <div class="max-w-md mx-auto">
              <button type="submit" class="w-full bg-blue-500 text-white py-3 rounded-lg font-medium hover:bg-blue-600 transition-colors">提交订单</button>
            </div>
          </div>
        </form>
      </div>

      
    </main>
  </div>
</template>

<script>
import axios from 'axios'
import HeaderActions from '../components/HeaderActions.vue'
export default {
  name: 'OrderPublish',
  components: { HeaderActions },
  data() {
    return {
      form: {
        itemType: '',
        itemCount: '',
        itemDesc: '',
        pickupLocation: '',
        pickupRef: '',
        pickupTime: '',
        pickupRange: '',
        dropoffLocation: '',
        dropoffDetail: '',
        remark: '',
        totalPrice: null
      },
      useTimeRange: true
    }
  },
  methods: {
    async prefillFromProfile() {
      const userId = localStorage.getItem('userId')
      if (!userId) return
      try {
        // 默认地址
        const { data } = await axios.get(`/api/addresses/${userId}`)
        const list = (data && (data.data || data)) || []
        let addr = list.find(a => a.is_default === 1 || a.is_default === true)
        if (!addr && list.length) addr = list[0]
        if (addr) {
          const full = addr.full_address || ''
          // 优先按空格拆分： "9栋 9-307"
          if (full.includes(' ')) {
            const i = full.indexOf(' ')
            this.form.dropoffLocation = full.slice(0, i)
            this.form.dropoffDetail = full.slice(i + 1)
          } else {
            // 尝试用常见分隔符
            const parts = full.split(/[,，-]/)
            this.form.dropoffLocation = parts[0] || ''
            this.form.dropoffDetail = parts.slice(1).join('-') || ''
          }
        }
        // 个人资料（如果需要可用作备注模板）
        const prof = await axios.get(`/api/users/profile/${userId}`)
        const p = (prof.data && prof.data.data) || {}
        if (p.nickname && !this.form.remark) {
          this.form.remark = `下单者：${p.nickname}`
        }
      } catch (e) {
        // 静默失败
      }
    },
    async handleSubmit() {
      const userId = Number(localStorage.getItem('userId'))
      if (!userId) { alert('请先登录'); this.$router.push('/login'); return }
      if (!this.form.pickupLocation) { alert('请选择取件地点'); return }
      if (!this.form.dropoffLocation) { alert('请选择送达地点'); return }
      if (this.form.totalPrice === null || isNaN(this.form.totalPrice)) { alert('请输入订单总价'); return }
      try {
        const normalizeDateTime = (v) => {
          if (!v) return null
          let s = String(v).trim()
          if (s.includes('T')) s = s.replace('T', ' ')
          // yyyy-MM-dd HH:mm -> append seconds
          if (/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}$/.test(s)) s = s + ':00'
          if (/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(s)) return s
          return null
        }
        const pad = (n) => (n < 10 ? '0' + n : '' + n)
        const todayMidForRange = (range) => {
          const now = new Date()
          const y = now.getFullYear(), m = pad(now.getMonth()+1), d = pad(now.getDate())
          if (range === 'morning') return `${y}-${m}-${d} 10:00:00`
          if (range === 'afternoon') return `${y}-${m}-${d} 15:00:00`
          if (range === 'evening') return `${y}-${m}-${d} 20:00:00`
          return null
        }
        const rangeLabel = (range) => range==='morning'?'上午(08:00-12:00)':range==='afternoon'?'下午(12:00-18:00)':range==='evening'?'晚上(18:00-22:00)':''

        let pickupTimeToSend = null
        let noteExtra = ''
        if (this.useTimeRange && this.form.pickupRange) {
          pickupTimeToSend = todayMidForRange(this.form.pickupRange)
          noteExtra = rangeLabel(this.form.pickupRange)
        } else {
          pickupTimeToSend = normalizeDateTime(this.form.pickupTime)
        }
        
        // 确保delivery_time不为null，提供默认值
        if (!pickupTimeToSend) {
          const now = new Date()
          const y = now.getFullYear()
          const m = String(now.getMonth() + 1).padStart(2, '0')
          const d = String(now.getDate()).padStart(2, '0')
          const h = String(now.getHours()).padStart(2, '0')
          const min = String(now.getMinutes()).padStart(2, '0')
          pickupTimeToSend = `${y}-${m}-${d} ${h}:${min}:00`
        }
        const noteParts = [
          this.form.remark ? `备注：${this.form.remark}` : '',
          this.form.itemDesc ? `物品描述：${this.form.itemDesc}` : '',
          noteExtra ? `期望时间段：${noteExtra}` : ''
        ].filter(Boolean)

        const payload = {
          userId: userId, // 后端会自动查找order_user_id
          pickup_location: this.form.pickupLocation,
          delivery_address: `${this.form.dropoffLocation}${this.form.dropoffDetail ? ' ' + this.form.dropoffDetail : ''}`.trim(),
          suggested_fee: Number(this.form.totalPrice || 0),
          note: noteParts.join(' \n'),
          express_type: this.form.itemType || null,
          express_company: '其他', // 添加快递公司字段，设置默认值
          pickup_code: this.form.pickupRef || null,
          package_size: 'medium', // 使用合理的默认值，而不是物品数量
          delivery_time: pickupTimeToSend // 修改字段名为delivery_time，与后端保持一致
        }
        console.log('📝 前端发送订单请求:', payload);
        console.log('📝 用户ID:', userId);
        const response = await axios.post('/api/orders', payload)
        if (response.data && response.data.success) {
          alert('订单提交成功！')
          this.$router.push('/order/my')
        } else {
          alert(response.data?.message || '下单失败，请稍后再试')
        }
      } catch (e) {
        console.error('下单失败', e)
        console.error('详细错误信息:', JSON.stringify(e.response?.data || {}))
        // 显示更详细的错误信息，包括后端返回的所有可用错误信息
        const errorDetails = [];
        errorDetails.push('🚨 下单失败！详细错误信息：');
        if (e.response) {
          errorDetails.push(`🔹 服务器响应错误: ${e.response.status}`);
          if (e.response.data) {
            const data = e.response.data;
            errorDetails.push(`🔹 错误信息: ${data.message || data.error || '无详细信息'}`);
            if (data.errorCode) errorDetails.push(`🔹 错误代码: ${data.errorCode}`);
            if (data.sqlMessage) errorDetails.push(`🔹 数据库错误: ${data.sqlMessage}`);
          }
        } else if (e.request) {
          errorDetails.push('🔹 请求发送失败，请检查网络连接');
        } else {
          errorDetails.push(`🔹 请求配置错误: ${e.message}`);
        }
        
        const errorMessage = errorDetails.join('\n');
        alert(errorMessage);
        console.log('请尝试重新下单，或联系管理员');
      }
    },
    logout() {
      localStorage.removeItem('userToken')
      this.$router.push('/login')
    }
  },
  mounted() {
    this.prefillFromProfile()
  }
}
</script>


